var app = getApp()
Page({
  data: {
    pics: [],
    people_type: "100",
    isShow: true,
    pics2: [],
    background: ['demo-text-1', 'demo-text-2', 'demo-text-3'],
    indicatorDots: true,
    vertical: false,
    autoplay: true,//轮播1是否自动播放
    circular: false,
    interval: 2000,
    duration: 500,
    previousMargin: 0,
    nextMargin: 0,
    curIndex: 0,  //当前显示的view下标
    swiperList: [1,2], //轮播数据列表
    winWidth: 0,  //设备宽度；
    winHeight: 0,   //设备高度；
    itemWidth: 0, //单个轮播图swiper-item的宽度；
    itemHeight: 0,//单个轮播图swiper-item的高度；
    allWidth: 0,  //轮播展示 swiper的总宽度；
    scale: 0.7,   //  缩放大小倍数；
    startClinetX: '', //触摸开始位置；
    startTimestamp: '', //触摸开始时间；
    translateDistance: 0,//动画移动的 距离；
    animationToLarge: {}, //从小变大的动画；
    animationToSmall: {},
    tempFilePaths: '',
    tabTouch: false, //tab点击会触发swiper的滚动，会导致调用两次相同的服务，使用此tag来阻止swiper调用服务，只是切换page
    window_width: wx.getSystemInfoSync().windowWidth || 375,// 单位是px
    tab_config: {
      tabs: ['最热', '换军装', '换制服', '换古装', '换婚纱', '换现代', '换心情'],// tabs
      fixed: false, // tabbar是否固定宽度
      active_tab: 0, //当前激活的tab
      item_width: 70,// 单位是px
      tab_left: 0, // 如果tabbar不是固定宽度，则目前左移的位置
      underline: {
        offset: 0, //下划线的位移
        margins: 20,  //下划线的左右间距
      }
    },
    swipe_config: {
      indicator_dots: false, // 不显示小圆点
      autoplay: false,// 自动切换
      interval: 2000,// 自动切换频率
      duration: 500, // 切换时间
      current: 0 // 当前激活的panel
    }
  },
  share: function () {
    console.log("这里是分享的事件");
    var openid = getApp().globalData.openid;
    var nickname = getApp().globalData.nickName;
    var that = this;
    wx.request({
      url: getApp().globalData.API_URI + '/index.php/face_share',
      data: { //appid 与 secret为对应小程序项目后台获取
        'openid': openid,
        'nickname': nickname,
      },
      header: {//请求头  
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        console.log(res.data)
        that.setData({ jifen: res.data.jifen, })
      }
    })
  },

  onShareAppMessage: function () {
    return {
      //title: '一键变脸 ',
      path: 'pages/index/index?openid=' + getApp().globalData.openid,
      imageUrl: "http://citiao.cndzys.com/images/hongbao.jpg",
      success: function (res) {
        // 转发成功
        console.log("转发成功");
      },
      fail: function (res) {
        // 转发失败
        console.log("转发失败");
      }
    }



  },

  //触摸开始的事件
  swiperTouchstart: function (e) {
    console.log('touchstart', e);
    let startClinetX = e.changedTouches[0].clientX;
    this.setData({
      startClinetX: startClinetX, //触摸开始位置；
      startTimestamp: e.timeStamp, //触摸开始时间；
      
    })
  },


  //触摸移动中的事件
  swiperTouchmove: function (e) {
    //console.log('touchmove', e);

  },

  //触摸结束事件
  swiperTouchend: function (e) {
    //console.log("我是男", e);

    let times = e.timeStamp - this.data.startTimestamp, //时间间隔；
      distance = e.changedTouches[0].clientX - this.data.startClinetX; //距离间隔；
    //判断
    if (times < 500 && Math.abs(distance) > 10) {
      let curIndex = this.data.curIndex;

      let x0 = this.data.itemWidth, x1 = this.data.translateDistance, x = 0;
      if (distance > 0) {

        curIndex = curIndex - 1
        if (curIndex < 0) {
          curIndex = 0; 
          x0 = 0;
        }
        x = x1 + x0;
      } else {

        // console.log('+1',x);
        curIndex = curIndex + 1
        if (curIndex >= this.data.swiperList.length) {
          curIndex = this.data.swiperList.length - 1;
          x0 = 0;
        }
        x = x1 - x0;
      }
      this.animationToLarge(curIndex, x);
      this.animationToSmall(curIndex, x);
      this.setData({
        curIndex: curIndex,
        translateDistance: x
      })

    } else {

    }
  },
  // 动画
  animationToLarge: function (curIndex, x) {
    this.data.people_type = this.data.people_type -= 1;
    if (this.data.people_type % 2=="0"){
      console.log("我是女");
      this.setData({ people_type1: "女生" })
      getApp().globalData.people_type1 = "女生";

      // if (getApp().globalData.sex=="1"){
      //   console.log("我是男");
      //   this.setData({ people_type1: "男生" })
      //   getApp().globalData.people_type1 = "男生";
      // }
      // else{
      //   console.log("我是女");
      //   this.setData({ people_type1: "女生" })
      //   getApp().globalData.people_type1 = "女生";
      // }

    }
    else{
      console.log("我是男");
      this.setData({ people_type1: "男生" })
      getApp().globalData.people_type1 = "男生";

      // if (getApp().globalData.sex == "1") {
      //   console.log("我是女生");
      //   this.setData({ people_type1: "女生" })
      //   getApp().globalData.people_type1 = "女生";
      // }
      // else {
      //   console.log("我是男");
      //   this.setData({ people_type1: "男生" })
      //   getApp().globalData.people_type1 = "男生";
      // }
    }

    
    this.animation.translateX(x).scale(1).step()
    this.setData({
      animationToLarge: this.animation.export()
    })
  },

  onGotUserInfo: function (e) {
    console.log("============")
    console.log(e.detail.errMsg)
    console.log(e.detail.userInfo)
    console.log(e.detail.rawData)
    getApp().globalData.nickName = e.detail.userInfo.nickName;
    getApp().globalData.sex = e.detail.userInfo.sex;
    getApp().globalData.avatarUrl = e.detail.userInfo.avatarUrl;
    this.updateUserInfo(e.detail.userInfo);
    wx.navigateBack({
    })
  },
  updateUserInfo: function (options) {
    this.setData({ dlts: "2" })
    wx.request({
      url: getApp().globalData.API_URI + '/index.php/face_updateUserInfo',
      header: {//请求头  
        "Content-Type": "applciation/json"
      },
      data: {
        openid: getApp().globalData.openid,
        avatarUrl: options.avatarUrl,
        nickname: options.nickName,
        city: options.city,
        country: options.country,
        language: options.language,
        gender: options.gender,
        province: options.province
      },
      method: 'GET',
      success: function (e) {
        console.log(e)
      }
    })
  },
  animationToSmall: function (curIndex, x) {
    this.animation.translateX(x).scale(0.7).step()
    this.setData({
      animationToSmall: this.animation.export()
    })
  },

  //弹出每日领取
  info: function () {
    this.setData({
      text: "1",
    })
  },
  //弹出积分详情
  jifen_open: function () {
    this.setData({
      text1: "1",
    })
  },
  //关闭积分详情
  jifen_close: function () {
    this.setData({
      text1: "2",
    })
  },
  //登录检测
  dljc: function (data) {

    if (data == "首次进来") {
      console.log("这里是首次进来的66");
      
       return;
    }
    var openid = getApp().globalData.openid;
    var nickname = getApp().globalData.nickName;
    var that = this;
    wx.request({
      url: getApp().globalData.API_URI + '/index.php/face_dljc',
      data: { //appid 与 secret为对应小程序项目后台获取
        'openid': openid,
        'nickname': nickname,
      },
      header: {//请求头  
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        that.setData({ jifen: res.data.jifen })
        console.log(res.data)
        if (res.data.error == "1") {
          that.setData({ text: 2 })
        }
      }
    })
  },
  //推荐人检测
  tjrjc: function () {
    console.log("这个是推荐人的OPENID");
    console.log(getApp().globalData.nickName);
    //this.setData({ referees: referees })
    var referees = getApp().globalData.referees;
    var openid = getApp().globalData.openid;
    var nickname = getApp().globalData.nickName;
    var that = this;
    // if (!referees) {
    //   //that.setData({ tjr_openid: "推荐人为空" })
    //   console.log("推荐人为空");
    //   //var tjr_openid="111";
    //   return;
    // }
    //that.setData({ tjr_openid: referees })
    wx.request({
      url: getApp().globalData.API_URI + '/index.php/face_referees',
      data: { //appid 与 secret为对应小程序项目后台获取
        'openid': openid,
        'nickname': nickname,
        'tjr_openid': referees,
        //'tjr_openid': 'oWwy45TGypCL-4rIYWVLG8xco7JY',
        

      },
      header: {//请求头  
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        that.setData({ jifen: res.data.jifen })
        console.log(res.data)
        // if (res.data.error == "1") {
        //   that.setData({ text: 2 })
        // }
      }
    })
  },
  onShow: function () {
    var that = this;
    if (getApp().globalData.openid == '') {
      console.log("onShow1");
      setTimeout(function () {
        //检测是否有推荐人
        var nickName = getApp().globalData.nickName;
        console.log('onShow1==nickname=' + nickName);
        if (nickName == "") {
          var data = "首次进来";
          console.log("首次进来");
          that.dljc(data);
        }
        else{
          console.log("不是首次进来");
          that.dljc();
        }
        
      }, 1000);
    }
    else {
      console.log("onShow2");
      //检测是否有推荐人
      that.dljc();
    }


  },

  getOpenid: function () {
    console.log("我是全局方法getOpenid");
    var that=this
    wx.login({
      //获取code
      success: function (res) {
        var code = res.code //返回code
        console.log('我是全局方法里的code=' + code)
        wx.request({
          url: getApp().globalData.API_URI + '/demo2.php',
          data: { //appid 与 secret为对应小程序项目后台获取
            'code': code,
            'appid': getApp().globalData.appid,
            'secret': getApp().globalData.secret,
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: function (res) {
            var openid = res.data
            console.log('我是全局方法里的openid=' + openid);
            getApp().globalData.openid = openid;
            that.getWXUserInfo();
          }
        })
      }
    })
  },


  getWXUserInfo: function () {
    console.log("我是getWXUserInfo方法")
    var that = this
    wx.request({
      url: getApp().globalData.API_URI + '/index.php/face_getUserInfo',
      data: { //appid 与 secret为对应小程序项目后台获取
        'openid': getApp().globalData.openid,
      },
      header: {//请求头  
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function (res) {
        console.log(res.data)
        if (!res.data.error) {
          console.log("这里是首页变量的dlts==0")
          getApp().globalData.nickName = res.data.nickname;
          getApp().globalData.avatarUrl = res.data.avatar_url;
          getApp().globalData.sex = res.data.sex;
          getApp().globalData.dlts = "0";
          that.setData({ dlts: "0" })
        } else {
          // wx.navigateTo({
          //   url: '../authorization/index',
          // })
          console.log("这里是首页变量的dlts==1")
          getApp().globalData.dlts = "1";
          that.setData({ dlts: "1" })
        }
        that.dljc();
        if (getApp().globalData.referees !="没有推荐人"){
          that.tjrjc();
        }
        
      }
    })
  },


  onLoad: function (options) {
    var that = this;
    getApp().globalData.people_type1 = "女生";
    //检测是否有推荐人
    if (options.openid) {
      var referees = options.openid;
    } else {
      var referees = "没有推荐人";
    }
    getApp().globalData.referees = referees;
    that.getOpenid();
    //var referees= options.openid;

    
    // console.log("首页的11dlts=" + getApp().globalData.dlts);
    // if (getApp().globalData.dlts=="1"){
    //   that.setData({ dlts: "1" })
    // }
    // console.log("openid=" + getApp().globalData.dlts);
    // if (getApp().globalData.openid == '') {
    //   setTimeout(function () {
    //     //console.log("2");
    //     // console.log("openid=" + getApp().globalData.openid);
    //     // console.log("sex=" + getApp().globalData.sex);
    //     // if (getApp().globalData.sex == "1") {
    //     //   console.log("男生进来了");
    //     //   that.setData({ people_type1: "男生" })
    //     //   that.setData({ man: "1" })
    //     //   getApp().globalData.people_type1 = "男生";
    //     // }
    //     // else {
    //     //   console.log("女生进来了");
    //     //   that.setData({ woman: "1" })
    //     //   that.setData({ people_type1: "女生" })
    //     //   getApp().globalData.people_type1 = "女生";
    //     // }
    //     //检测是否有推荐人
    //     console.log("首页的22dlts=" + getApp().globalData.dlts);
    //     if (getApp().globalData.dlts == "1") {
    //       that.setData({ dlts: "1" })
    //     }
    //     var referees = options.openid;
    //     that.tjrjc(referees);
    //   }, 1000);
    // }
    // else {
    //   var referees = options.openid;
    //   that.tjrjc(referees);
    // }
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        let w = res.windowWidth, h = res.windowHeight;
        let allWidth = that.data.swiperList.length * (w * 0.66);
        that.setData({
          winWidth: w,
          winHeight: h,
          itemWidth: w * 0.66,
          allWidth: allWidth
        })
      },
    })
    this.animation = wx.createAnimation({
      transformOrigin: "50% 50%",
      duration: 500,
      timingFunction: "ease-out",
      delay: 0
    })
  },



  
  content: function () {
    wx.navigateTo({
      url: '../content/content',
    })
  },
  //本地相册
  chooseImage: function () {

    var that=this 
    // console.log("5555");
    // console.log(that.data.people_type1);die;

    that.setData({ loand1: "2"})
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', ''], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album'], // album 从相册选图，camera 使用相机，默认二者都有
      //sourceType: ['camera'], // album 从相册选图，camera 使用相机，默认二者都有
      //sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        // success
        var imgSrc = res.tempFilePaths;
        var size = res.tempFiles['0'].size;
        if (size >= 4551206){
          //console.log("====================="); console.log(size); die;
          that.setData({ cuowu: 1 })
          that.setData({ loand1: 1 })
          setTimeout(function () {
            that.setData({ cuowu: 2 })
          }, 2000)
          return;
        }
        wx.uploadFile({
          url: getApp().globalData.API_URI + '/upload1.php',
          filePath: imgSrc['0'],
          name: 'file',
          success: function (res) {
            //打印
            that.setData({ loand1: "1" })
            console.log("回调回来的图片名称")
            var img = res.data
            console.log(img)
            wx.navigateTo({ url: '../content/content?img_url=' + img + '&people_type1=' + that.data.people_type1})
          }
        })
      },
      fail: function () {
        that.setData({ loand1: "1" })
      },
      complete: function () {
        // complete
      }
    })
  },
  //摄像头
  chooseImage1: function () {
    var that = this 
    that.setData({ loand1: "2" })
    wx.chooseImage({
      count: 1, // 最多可以选择的图片张数，默认9
      sizeType: ['original', ''], // original 原图，compressed 压缩图，默认二者都有
      //sourceType: ['album'], // album 从相册选图，camera 使用相机，默认二者都有
      sourceType: ['camera'], // album 从相册选图，camera 使用相机，默认二者都有
      //sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function (res) {
        // success
        var imgSrc = res.tempFilePaths;

        var size = res.tempFiles['0'].size;
        if (size >= 4551206) {
          //console.log("====================="); console.log(size); die;
          that.setData({ cuowu: 1 })
          that.setData({ loand1: 1 })
          setTimeout(function () {
            that.setData({ cuowu: 2 })
          }, 2000)
          return;
        }
        
        console.log(imgSrc)
        that.setData({ loand1: "1" })
        wx.uploadFile({
          url: getApp().globalData.API_URI + '/upload1.php',
          filePath: imgSrc['0'],
          name: 'file',
          success: function (res) {
            //打印
            console.log("回调回来的图片名称")
            var img = res.data
            console.log(img)
            wx.navigateTo({
              url: '../content/content?img_url=' + img + '&people_type1=' + that.data.people_type1,

            })

          }
        })

      },
      fail: function () {
        that.setData({ loand1: "1" })
      },
      complete: function () {
        // complete
      }
    })
  },
  // 图片预览
  previewImage: function (e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.pics
    })
  },

  /**
   * 更换页面到指定page ，从0开始
   */
  updateSelectedPage(page) {
    let that = this;
    //console.log("========== updateSelectedPage" + page);
    let { window_width, tab_config, swipe_config } = this.data;
    let underline_offset = tab_config.item_width * page;

    tab_config.active_tab = page;
    swipe_config.current = page;
    tab_config.underline.offset = underline_offset;
    if (!tab_config.fixed) {
      // 如果tab不是固定的 就要 检测tab是否被遮挡
      let show_item_num = Math.round(window_width / tab_config.item_width); // 一个界面完整显示的tab item个数
      let min_left_item = tab_config.item_width * (page - show_item_num + 1); // 最小scroll-left 
      let max_left_item = tab_config.item_width * page; //  最大scroll-left
      if (tab_config.tab_left < min_left_item || tab_config.tab_left > max_left_item) {
        // 如果被遮挡，则要移到当前元素居中位置
        tab_config.tab_left = max_left_item - (window_width - tab_config.item_width) / 2;
      }
    }
    that.setData({
      "tab_config": tab_config,
      "swipe_config": swipe_config
    });
    //调用页面的接口更新页面
    that.loadOrderList(page);
  },

  /**
   * tab的点击事件
   */
  handlerTabTap(e) {
    this.setData({
      tabTouch: true
    })
    this.updateSelectedPage(e.currentTarget.dataset.index);
  },

  /**
   * swiper的滑动事件
   */
  bindChange(e) {
    if (!this.data.tabTouch) {
      // console.log("===== swiperChange " + e.detail.current);
      this.updateSelectedPage(e.detail.current);
    }
  },

})
